import json
from django.shortcuts import render, redirect
from django.views.generic.base import View
from .forms import LoginForm, UserPwdModifyForm
from django.http.response import HttpResponseRedirect, HttpResponse, JsonResponse  # ajax返回数据
from django.contrib.auth import authenticate, login, logout
from django.urls import reverse
from django.contrib.auth.models import Group
from django.contrib.auth.hashers import make_password
from utils.mixin_utils import LoginRequiredMixin
from .models import UserProfile, Log, Department, Position, Msg, Menu, CustomPerms
from utils.sent_mail import SentMail
import random, datetime, re, os
from utils.check_permission import check_custom_perms
from django.db.models import Q
from salary.settings import BASE_DIR, Corpid_, Login_Scret, Login_Agentid, Redirect_uri
import pandas
import requests
from utils.tree_dept import getAllSubDept


# 日期对比函数-用于验证码是否过期比较
def DateTimeCompare(expire_time):
    now = datetime.datetime.now()
    now_day = now.strftime('%y%m%d')
    now_time = now.strftime('%H%M%S')
    expire_time_day = expire_time.strftime('%y%m%d')
    expire_time_time = expire_time.strftime('%H%M%S')
    if now_day == expire_time_day:  # 同一天
        if now_time < expire_time_time:  # 验证码未超时
            return True
        else:
            return False
    else:
        return False


# 使用用户邮箱或者手机号码作为用户名登录
from django.contrib.auth.backends import ModelBackend


class EmailBackend(ModelBackend):
    def authenticate(self, request, username=None, password=None, **kwargs):
        try:
            user = UserProfile.objects.get(Q(mobile=username) | Q(email=username) | Q(username=username))
        except UserProfile.DoesNotExist:  # 可以捕获除与程序退出sys.exit()相关之外的所有异常
            return None
        if user.check_password(password):
            return user

    def get_user(self, user_id):
        try:
            return UserProfile.objects.get(id=user_id)
        except UserProfile.DoesNotExist:
            return None


# 用户登录
class UserLoginView(View):
    def get(self, request):
        return render(request, 'user/login_v3.html')

    def post(self, request):
        login_form = LoginForm(request.POST)
        if login_form.is_valid():
            user_name = request.POST.get('username').strip()
            pass_word = request.POST.get('password').strip()
            u_id = UserProfile.objects.filter(Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name)).all()
            if not u_id:
                return render(request, 'user/login_v3.html', {'msg': '用户不存在！'})
            else:
                user = authenticate(request, username=user_name, password=pass_word)
                if user:
                    # 检查用户是否第一次登录
                    force_change_pass = UserProfile.objects.filter(
                        Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name)).all()
                    for i in force_change_pass:
                        if i.is_active == 0:
                            return render(request, 'user/login_v3.html', {'msg': '用户已被禁用，请联系管理员！'})
                        elif i.force_change_passwd == 1:
                            # 跳转首次登录页，更改密码
                            return render(request, 'user/first_login.html', {'user_name': user_name})
                        else:
                            # 登录系统
                            login(request, user)
                            # 记录用户登录动作
                            new_log = Log(username=user_name, content='用户登录，登录成功！')
                            new_log.save()
                            return HttpResponseRedirect(reverse('index'))
                else:
                    # 记录用户登录动作
                    new_log = Log(username=user_name, content='用户登录，登录失败，密码错误！')
                    new_log.save()
                    return render(request, 'user/login_v3.html', {'msg': '密码认证失败！'})

        else:
            return render(request, 'user/login_v3.html', {'msg': '认证失败！', 'login_form': login_form})


# 忘记密码，通过邮件找回密码
class ForGotPasswordView(View):
    def get(self, request):
        return render(request, 'user/forgot_password.html')

    def post(self, request):
        user_name = request.POST.get("user_name")
        code = request.POST.get('code')
        pw1 = request.POST.get('pw1')
        pw2 = request.POST.get('pw2')
        # 根据post传入的数据，判断用户的操作
        if user_name and code and pw1 and pw2:
            # 重置密码
            # 判断验证码是否有效
            user_info = UserProfile.objects.filter(
                Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name)).all()
            if user_info:
                sys_code = user_info[0].code
                expire_time = user_info[0].code_expire
                if code == sys_code:
                    if DateTimeCompare(expire_time):
                        # 验证码有效且未过期
                        if pw1 == pw2:
                            # 更新密码
                            UserProfile.objects.filter(
                                Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name)).update(
                                password=make_password(pw1))
                            # 记录用户动作
                            new_log = Log(username=user_name, content='密码修改成功！')
                            new_log.save()
                            return JsonResponse({'status': 3, 'info': '密码更新成功！请重新登录！'})
                        else:
                            return JsonResponse({'status': 0, 'info': '两次输入的密码不一致，请重新输入！'})
                    else:
                        return JsonResponse({'status': 0, 'info': '验证码已过期！请重新发送验证码！'})
                else:
                    return JsonResponse({'status': 0, 'info': '验证码错误！'})
            else:
                return JsonResponse({'status': 0, 'info': '提供的信息无效，无法找到对应的用户！'})
        elif user_name and not code:
            # 检查用户名和对应的邮箱是否存在
            user_info = UserProfile.objects.filter(
                Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name)).all()
            if user_info:
                for i in user_info:
                    email = i.email
                    if email:
                        # 发送验证码
                        # 随机生成一个6位数字
                        sys_code = random.randint(100000, 999999)
                        # 获取当前时间然后再加10分钟，作为验证码过期时间
                        expire_time = datetime.datetime.now() + datetime.timedelta(minutes=10)
                        # 将验证码和过期时间填充入数据库
                        UserProfile.objects.filter(
                            Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name)).update(code=sys_code,
                                                                                                     code_expire=expire_time)
                        # print(sys_code, expire_time)
                        # 调用SendMail发送邮件
                        contents = """
                        %s，您好！<br>您正在申请重置密码，验证码是：<br>
                        <h1>%s</h1><br>
                        验证码将在：%s过期，请及时操作。<br>
                        """ % (user_name, sys_code, expire_time.strftime("%Y-%m-%d %H:%M:%S"))
                        # 使用线程发送邮件
                        import threading
                        threading.Thread(target=SentMail, args=('密码重置', contents, email)).start()
                        return JsonResponse({'status': 1, 'info': '验证码发送成功，请登录邮箱查看，然后将验证码输入到验证码框中。'})
                    else:
                        return JsonResponse({'status': 0, 'info': '此用户没有填写邮件地址，无法通过自助方式重置密码，请联系管理员处理！'})
            else:
                return JsonResponse({'status': 0, 'info': '用户不存在！请确认用户名是否有误！'})
        else:
            return JsonResponse({'status': 0, 'info': '输入有误，请确认！'})


# 首次登录-强制更改密码
class FirstLoginView(View):
    def get(self, request):
        return render(request, 'user/first_login.html')

    def post(self, request):
        user_name = request.POST.get('user_name')
        pwd = request.POST.get('pwd')
        pwd1 = request.POST.get('pw1')
        pwd2 = request.POST.get('pw2')
        user = authenticate(username=user_name, password=pwd)
        if not user:
            return JsonResponse({'status': 0, 'info': '原密码验证失败，请输入正确的密码！'})
        else:
            if pwd1 == pwd2:
                user2 = authenticate(username=user_name, password=pwd1)
                if user2:
                    return JsonResponse({'status': 0, 'info': '新密码不能和原密码一致！'})
                else:
                    user.password = make_password(pwd1)
                    user.save()
                    # 修改用户的强制修改密码状态，
                    UserProfile.objects.filter(Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name)).update(
                        force_change_passwd=0)
                    # 记录用户动作
                    new_log = Log(username=user_name, content='密码修改成功！')
                    new_log.save()
                    return JsonResponse({'status': 1, 'info': '密码修改成功，请重新登录！'})
            else:
                return JsonResponse({'status': 0, 'info': '两次输入的密码不一致，请重新输入！'})


# 用户退出
class UserLogoutView(View):
    def get(self, request):
        logout(request)
        response = redirect(reverse('login:user_login'))
        response.delete_cookie('username')
        return response


# 用户修改密码----成员视图
class UserPwdModifyView(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'user/user_pwd_modify.html')

    def post(self, request):
        user_name = UserProfile.objects.get(username=request.user.username)
        pwd = request.POST.get('pwd')
        pwd1 = request.POST.get('pw1')
        pwd2 = request.POST.get('pw2')
        user = authenticate(username=user_name, password=pwd)
        if not user:
            return JsonResponse({'status': 0, 'info': '原密码验证失败，请输入正确的密码！'})
        else:
            if pwd1 == pwd2:
                user2 = authenticate(username=user_name, password=pwd1)
                if user2:
                    return JsonResponse({'status': 0, 'info': '新密码不能和原密码一致！'})
                else:
                    user.password = make_password(pwd1)
                    user.save()
                    # 记录用户动作
                    new_log = Log(username=user_name, scope='用户模块', type='主动修改密码', content='密码修改成功！')
                    new_log.save()
                    return JsonResponse({'status': 1, 'info': '密码修改成功，请重新登录！'})
            else:
                return JsonResponse({'status': 0, 'info': '两次输入的密码不一致，请重新输入！'})


# 用户信息修改----成员视图
class UserModifyView(LoginRequiredMixin, View):
    def get(self, request):
        uuid = request.user.id
        perms = check_custom_perms(2, uuid, "edit")
        if not perms:
            return render(request, 'deny.html')
        # 获取传入的uid
        uid = request.GET.get('uid')
        if not uid:
            uid = request.user.id
            # 根据用户ID，获取用户数据
            user_info = UserProfile.objects.filter(id=uid).all()
        else:
            user_info = UserProfile.objects.filter(id=uid).all()
        user_role = user_info[0].role
        # 获取用户组
        Department_info = Department.objects.all()
        # 提取角色
        role_info = Group.objects.all()
        # 获取用户角色小于等于5的人员，作为部门领导选择项
        direct_leader = UserProfile.objects.filter(role__lte=5).all().exclude(username='admin')
        # 获取所有职位
        all_position = Position.objects.all()
        return render(request, 'user/user_modify.html', {'user_info': user_info, 'Department_info': Department_info,
                                                         'role_info': role_info,
                                                         'user_role': user_role,
                                                         'direct_leader': direct_leader, 'all_position': all_position})

    def post(self, request):
        user_id = request.POST.get('user_id')
        user_name = request.user.username
        # 从前端ajax的POST提交获取数据
        email = request.POST.get('email')
        mobile = request.POST.get('mobile')
        department = request.POST.get('department')
        is_superuser = request.POST.get('is_superuser')
        role = request.POST.get('role')
        is_active = request.POST.get('is_active')
        pw1 = request.POST.get('pw1')
        pw2 = request.POST.get('pw2')
        is_charger = request.POST.get('is_charger')
        direct_leader = request.POST.get('direct_leader')
        msg = ''
        # 职位
        position = request.POST.get('position')
        # 判断用户是否为部门负责人
        if is_charger:
            if int(is_charger) == 1:
                # 此用户是部门负责人
                # 更新用户名到部门负责人
                u_object = UserProfile.objects.filter(id=user_id).all()
                Department.objects.filter(id=department).update(leader=u_object[0].username)
                UserProfile.objects.filter(id=user_id).update(is_staff=1)
        # 提取用户原来的数据
        user_info = UserProfile.objects.filter(id=user_id).all()
        for u in user_info:
            u_eamil = u.email
            u_mobile = u.mobile
            u_department = u.department
            u_role = u.role
            u_direct_leader = u.direct_leader
            u_position = u.position
            if u.is_superuser:
                u_is_superuser = '1'
            else:
                u_is_superuser = '0'
            if u.is_active:
                u_is_active = '1'
            else:
                u_is_active = '0'
            # 更新到数据库
            # 修改用户角色
            if user_id and role and role != u_role:
                UserProfile.objects.filter(id=user_id).update(role=role)
                # 记录用户动作
                content_log = '用户角色--' + str(u_role) + '-->' + str(role) + '修改成功'
                new_log = Log(username=user_name, content=content_log)
                new_log.save()
            # 修改用户邮箱
            if user_id and email and email != u_eamil:
                UserProfile.objects.filter(id=user_id).update(email=email)
                # 记录用户动作
                content_log = '邮箱--' + str(u_eamil) + '-->' + email + '修改成功'
                new_log = Log(username=user_name, content=content_log)
                new_log.save()
            # 修改用户直属领导
            if user_id and direct_leader and direct_leader != u_direct_leader:
                UserProfile.objects.filter(id=user_id).update(direct_leader=direct_leader)
                # 记录用户动作
                content_log = '直属领导--' + str(u_eamil) + '-->' + email + '修改成功'
                new_log = Log(username=user_name, content=content_log)
                new_log.save()
            # 修改用户手机号码
            if user_id and mobile and mobile != u_mobile:
                UserProfile.objects.filter(id=user_id).update(mobile=mobile)
                # 记录用户动作
                content_log = '手机号码--' + str(u_mobile) + '-->' + mobile + '修改成功'
                new_log = Log(username=user_name, content=content_log)
                new_log.save()
            # 修改用户部门
            if user_id and department and department != str(u_department):
                UserProfile.objects.filter(id=user_id).update(department=department)
                # 记录用户动作
                content_log = '用户部门--' + str(u_department) + '-->' + str(department) + '修改成功'
                new_log = Log(username=user_name, content=content_log)
                new_log.save()
            # 修改用户职位
            if user_id and position and position != str(u_position):
                UserProfile.objects.filter(id=user_id).update(position=position)
                # 记录用户动作
                content_log = '用户职位--' + str(u_position) + '-->' + str(position) + '修改成功'
                new_log = Log(username=user_name, content=content_log)
                new_log.save()
            if user_id and is_superuser and is_superuser and is_superuser != u_is_superuser:
                is_superuser = int(is_superuser)
                UserProfile.objects.filter(id=user_id).update(is_superuser=is_superuser)
                # 记录用户动作
                content_log = '超级管理员状态--' + str(u_is_superuser) + '-->' + '修改成功'
                new_log = Log(username=user_name, content=content_log)
                new_log.save()
            if user_id and is_active and is_active != u_is_active:
                is_active = int(is_active)
                UserProfile.objects.filter(id=user_id).update(is_active=is_active)
                # 记录用户动作
                content_log = '状态--' + str(u_is_active) + '-->' + str(is_active) + '修改成功'
                new_log = Log(username=user_name, content=content_log)
                new_log.save()
            if pw1 and pw1 == pw2:
                if len(pw1) >= 6:
                    UserProfile.objects.filter(id=user_id).update(password=make_password(pw1))
                    # 记录用户动作
                    new_log = Log(username=user_name, content='密码-->修改成功！')
                    new_log.save()
                else:
                    msg = ({'status': 0, 'info': '密码更新失败，强度不够！'})
        if msg != '':
            return JsonResponse(msg)
        else:
            return JsonResponse({'status': 1, 'info': '用户信息更新成功！'})


# 创建用户----管理员视图
class UserAddView(LoginRequiredMixin, View):
    def get(self, request):
        uid = request.user.id
        perms = check_custom_perms(2, uid, "change")
        if not perms:
            return render(request, 'deny.html')
        # 提取角色
        role_info = Group.objects.all()
        # 获取用户组
        if request.user.is_superuser == 1:
            Department_info = Department.objects.all()
        elif request.user.is_staff == 1:
            user_info = UserProfile.objects.filter(id=request.user.id).all()
            Department_info = []
            for i in user_info:
                x = {}
                x['id'] = i.id
                x['name'] = i.department
                Department_info.append(x)
        else:
            Department_info = []
            return render(request, 'user/user_add.html', {'msg': '您没有权限增加用户！', 'Department_info': Department_info})
        # 获取用户角色小于等于5的人员，作为部门领导选择项
        direct_leader = UserProfile.objects.filter(position__role__lte=3).all().exclude(username='admin')
        # 获取职位信息
        all_position = Position.objects.all()
        return render(request, 'user/user_add.html', {'Department_info': Department_info, 'role_info': role_info,
                                                      'direct_leader': direct_leader, 'all_position': all_position})

    def post(self, request):
        # 从前端ajax的POST提交获取数据
        username = request.POST.get('username')
        email = request.POST.get('email')
        mobile = request.POST.get('mobile')
        is_superuser = request.POST.get('is_superuser')
        role = request.POST.get('role')
        is_active = request.POST.get('is_active')
        d_id = request.POST.get('department')
        is_charger = request.POST.get('is_charger')
        direct_leader = request.POST.get('direct_leader')
        position = request.POST.get('position')

        # 多做一步认证，确保ajax提交的数据是完整的
        if username and email and mobile:
            # 密码设置为admin123@
            password = 'pbkdf2_sha256$216000$KLneLROEK49e$QFWZIsOJI5xe87ha6Qk9NHrxvwMG35nneffXAs63IIo='
            is_staff = 0
            # 判断级别，然后设置对应的角色,小于3，则为部门主管以上级别，设置为管理员
            if position:
                check_position = Position.objects.filter(id=position).all()
                if check_position:
                    if check_position[0].role < 3:
                        is_staff = 1
            # 保存用户
            new_user = UserProfile(username=username, email=email, department_id=d_id, is_staff=is_staff,
                                   role_id=role, mobile=mobile, is_active=is_active, is_superuser=is_superuser,
                                   password=password, direct_leader=direct_leader, position_id=position)
            new_user.save()
            # 更新用户组
            # 首先获取用户对象
            u_object = UserProfile.objects.filter(username=username).all()
            if int(is_charger) == 1:
                # 此用户是部门负责人
                # 更新用户名到部门负责人
                Department.objects.filter(id=d_id).update(leader=u_object[0].username)
                # 记录用户动作
                contents = '管理员添加用户--' + username + '-->添加成功！'
                new_log = Log(username=username, content=contents)
                new_log.save()
            # 用户保存成功，返回结果
            return JsonResponse({'status': 1, 'info': '注册新用户成功！默认密码是：admin123@ '})
        else:
            return JsonResponse({'status': 0, 'info': '注册新用户失败，有部分字段未成功提交！'})


# 用户列表----管理员视图
def UserListView(request):
    uid = request.user.id
    perms = check_custom_perms(3, uid, "read")
    if not perms:
        return render(request, 'deny.html')
    users = UserProfile.objects.all()
    return render(request, 'user/user_list.html', {'users': users})


# 查看用户组----管理员视图
class DeptView(LoginRequiredMixin, View):
    def get(self, request):
        uid = request.user.id
        perms = check_custom_perms(4, uid, "read")
        if not perms:
            return render(request, 'deny.html')
        groups = Department.objects.all()
        return render(request, 'user/group.html', {'groups': groups})

    # 此处post作用为设置部门主管
    def post(self, request):
        leader_name = request.POST.get("select_leader")
        did = request.POST.get("select_did")
        if did and leader_name:
            # 检查用户是否存在
            u_data = UserProfile.objects.filter(username=leader_name).all()
            if u_data:
                # 先检查用户是否是本部门的成员
                if int(u_data[0].department_id) == int(did):
                    # 允许设置
                    if Department.objects.filter(id=did, leader=leader_name):
                        # 错误，新设置的和现有的主管一致
                        return JsonResponse({"status": 0, "info": "新部门主管和原部门主管是同一个人，不允许此操作！"})
                    else:
                        Department.objects.filter(id=did).update(leader=leader_name)
                        return JsonResponse({"status": 1, "info": "设置成功"})
                else:
                    return JsonResponse({"status": 0, "info": "部门主管只能是本部门的成员，请先将此用户部门修改为此部门！"})
            else:
                info = leader_name + "-用户不存在，设置为部门主管前，请确认账号已创建！"
                return JsonResponse({"status": 0, "info": info})
        else:
            return JsonResponse({"status": 0, "info": "数据不完整！"})


# 用户组管理，ajax请求获取用户部门的详细信息【部门主管，部门人数】
class getDeptDetailView(LoginRequiredMixin, View):
    def post(self, request):
        did = request.POST.get("id")
        dname = request.POST.get("name")
        # 1, 首先，根据部门ID，获取旗下有多少个子部门【只获取直属第一级的子部门，第二级往后的不获取】
        data = Department.objects.filter(pid=did).all()
        sub_dept = list()
        if data:
            for j in data:
                sub_dept.append(j.name)
        # 2，统计此部门一下的所有人数
        sub_dept_id = getAllSubDept(did)
        u_data = UserProfile.objects.filter(department_id__in=sub_dept_id).all()
        people_count = len(u_data)
        d_data = Department.objects.get(id=did)
        return JsonResponse({"status": 1, "info": "请求成功！", "did": did, "sub_dept": sub_dept,
                             "people_count": people_count, "dname": dname, "leader": d_data.leader})


# 新增用户组
class DeptAddView(LoginRequiredMixin, View):
    def get(self, request):
        uid = request.user.id
        perms = check_custom_perms(4, uid, "read")
        if not perms:
            return render(request, 'deny.html')
        return render(request, 'user/add_group.html')

    def post(self, request):
        uid = request.user.id
        perms = check_custom_perms(4, uid, "change")
        if not perms:
            return render(request, 'deny.html')
        name = request.POST.get('name')
        if name:
            new_group = Department(name=name)
            new_group.save()
            # 记录用户动作
            contents = name + '新增用户部门，增加成功！'
            new_log = Log(username=name, content=contents)
            new_log.save()
            return JsonResponse({'status': 1, 'info': '新增部门成功！'})
        return JsonResponse({'status': 0, 'info': '数据无效，请重试！'})


# 用户部门修改，ajax iframe层
class DeptModifyView(LoginRequiredMixin, View):
    def get(self, request):
        uid = request.user.id
        perms = check_custom_perms(4, uid, "read")
        if not perms:
            return render(request, 'deny.html')
        gid = request.GET.get('dept')
        Data = Department.objects.filter(id=gid).values('name')
        if Data:
            name = Data[0]['name']
            return render(request, 'user/group_modify.html', {'name': name})

    def post(self, request):
        uid = request.user.id
        perms = check_custom_perms(4, uid, "change")
        if not perms:
            return render(request, 'deny.html')
        old_name = request.POST.get('old_name')
        new_name = request.POST.get('new_name')
        if old_name and new_name:
            Department.objects.filter(name=old_name).update(name=new_name)
            # 记录用户动作
            content_log = str(old_name) + '-->' + new_name + '修改成功'
            new_log = Log(username=old_name, content=content_log)
            new_log.save()
            return JsonResponse({'status': 1, 'info': '部门修改成功！'})
        else:
            return JsonResponse({'status': 0, 'info': '传入的数据有误，请确认是否已经填写正确！'})


# 权限设置----管理员视图
class PermissionView(LoginRequiredMixin, View):
    def get(self, request, type_, to_id):
        uid = request.user.id
        perms = check_custom_perms(6, uid, "delete")
        if not perms:
            return render(request, 'deny.html')
        # 获取菜单数据
        menu_data = Menu.objects.all()
        if type_ == "user":
            # 针对用户设置权限
            custom_name = UserProfile.objects.get(id=to_id)
            custom_name = custom_name.username
        else:
            # 针对角色设置权限
            custom_name = Group.objects.get(id=to_id)
            custom_name = custom_name.name
        # 重新整合数据，获取现有的权限
        from utils.check_permission import check_role_perms
        new_data = []
        for j in menu_data:
            item = {}
            item["id"] = j.id
            item["pid"] = j.pid
            item["name"] = j.name
            item["show"] = j.show
            # 检查此权限
            if type_ == "user":
                item['r'] = check_custom_perms(j.id, to_id, 'read')
                item['c'] = check_custom_perms(j.id, to_id, 'change')
                item['d'] = check_custom_perms(j.id, to_id, 'delete')
            else:
                item['r'] = check_role_perms(j.id, to_id, 'read')
                item['c'] = check_role_perms(j.id, to_id, 'change')
                item['d'] = check_role_perms(j.id, to_id, 'delete')
            new_data.append(item)
        return render(request, 'user/permission.html', {'data': new_data, 'custom_name': custom_name})

    def post(self, request, type_, to_id):
        # 获取最大的菜单ID
        menu_data = Menu.objects.all().order_by("-id")
        max_num = menu_data[0].id
        # 循环获取权限值
        i = 1
        while i <= max_num:
            perms_name = "perms_" + str(i)
            mid_name = "mid_" + str(i)
            perms = request.POST.getlist(perms_name)
            mid = request.POST.get(mid_name)
            if perms and mid:
                # 新增数据
                if type_ == "user":
                    # 针对用户设置权限
                    for j in perms:
                        if not CustomPerms.objects.filter(to_menu_id=mid, type=j):
                            new = CustomPerms(to_menu_id=mid, type=j)
                            new.save()
                        data = CustomPerms.objects.get(to_menu_id=mid, type=j)
                        # 加入权限
                        data.perms.add(to_id)
                else:
                    # 针对角色设置权限
                    for j in perms:
                        if not CustomPerms.objects.filter(to_menu_id=mid, type=j):
                            new = CustomPerms(to_menu_id=mid, type=j)
                            new.save()
                        data = CustomPerms.objects.get(to_menu_id=mid, type=j)
                        # 加入权限
                        data.perms_group.add(to_id)
            elif mid:
                # 没有传入权限，只传入了ID
                # 空权限，需要删除此用户或者/角色的权限
                # 此处的空权限，代表前端已将此菜单的所有权限清空
                if type_ == "user":
                    # 针对用户设置权限
                    # 1,移除查看权限
                    if not CustomPerms.objects.filter(to_menu_id=mid, type=1):
                        new = CustomPerms(to_menu_id=mid, type=1)
                        new.save()
                    data = CustomPerms.objects.get(to_menu_id=mid, type=1)
                    # 删除权限
                    data.perms.remove(to_id)
                    # 2,移除新增/修改权限
                    if not CustomPerms.objects.filter(to_menu_id=mid, type=2):
                        new = CustomPerms(to_menu_id=mid, type=2)
                        new.save()
                    data = CustomPerms.objects.get(to_menu_id=mid, type=2)
                    # 删除权限
                    data.perms.remove(to_id)
                    # 3,移除删除权限
                    if not CustomPerms.objects.filter(to_menu_id=mid, type=3):
                        new = CustomPerms(to_menu_id=mid, type=3)
                        new.save()
                    data = CustomPerms.objects.get(to_menu_id=mid, type=3)
                    # 删除权限
                    data.perms.remove(to_id)
                else:
                    # 针对角色设置权限
                    # 1,移除查看权限
                    if not CustomPerms.objects.filter(to_menu_id=mid, type=1):
                        new = CustomPerms(to_menu_id=mid, type=1)
                        new.save()
                    data = CustomPerms.objects.get(to_menu_id=mid, type=1)
                    # 删除权限
                    data.perms_group.remove(to_id)
                    # 2,移除新增/修改权限
                    if not CustomPerms.objects.filter(to_menu_id=mid, type=2):
                        new = CustomPerms(to_menu_id=mid, type=2)
                        new.save()
                    data = CustomPerms.objects.get(to_menu_id=mid, type=2)
                    # 删除权限
                    data.perms_group.remove(to_id)
                    # 3,移除删除权限
                    if not CustomPerms.objects.filter(to_menu_id=mid, type=3):
                        new = CustomPerms(to_menu_id=mid, type=3)
                        new.save()
                    data = CustomPerms.objects.get(to_menu_id=mid, type=3)
                    # 删除权限
                    data.perms_group.remove(to_id)
            # 此条数据处理完成，递增1，处理下一条
            i = i + 1
        return JsonResponse({'status': 1, 'info': '保存成功！！'})


# 用户合法性检测，主要用于检测用户名是否重复，邮箱是否重复，手机是否重复
def UsernameCheck(request):
    username = request.POST.get('username')
    if username:
        check = UserProfile.objects.filter(username=username)
        if check:
            return JsonResponse({'status': '1', 'msg': '* 用户名已存在！'})
        else:
            return JsonResponse({'status': '2', 'msg': '√ 用户名可以使用！'})
    else:
        return JsonResponse({'status': '0', 'msg': '* 用户名不可为空！'})


def EmailCheck(request):
    email = request.POST.get('email')
    if email:
        check = UserProfile.objects.filter(email=email)
        if check:
            return JsonResponse({'status': '1', 'msg': '* 邮箱已存在！'})
        else:
            return JsonResponse({'status': '2', 'msg': '√ 邮箱可以使用！'})
    else:
        return JsonResponse({'status': '0', 'msg': '* 邮箱不可为空！'})


def MobileCheck(request):
    mobile = request.POST.get('mobile')
    if mobile:
        check = UserProfile.objects.filter(mobile=mobile)
        if check:
            return JsonResponse({'status': '1', 'msg': '* 手机号已存在！'})
        else:
            return JsonResponse({'status': '2', 'msg': '√ 手机号可以使用！'})
    else:
        return JsonResponse({'status': '0', 'msg': '* 手机号不可为空！'})


# log模块
class LogView(LoginRequiredMixin, View):
    def get(self, request):
        uid = request.user.id
        perms = check_custom_perms(8, uid, "read")
        if not perms:
            return render(request, 'deny.html')
        logs = Log.objects.all().order_by('-modify_time')
        return render(request, 'user/log.html', {'logs': logs})


# ajax 获取树形部门结构
class getDepartmentTreeView(LoginRequiredMixin, View):
    def get(self, request):
        top_Department = Department.objects.filter(pid=0).all()
        '''
        前端使用layui的tree组件，下面将部门目录处理为tree组件需要的格式
        '''
        top_dept = []
        for i in top_Department:
            x = {}
            x['id'] = i.id
            x['open'] = 'true'  # 此字段控制默认展开，如果不设置，layui默认为收缩
            x['name'] = i.name
            x['noRemoveBtn'] = 'true'
            # 二级目录
            children_data = Department.objects.filter(pid=i.id).all()
            if children_data:
                u = []  # 二级目录容器
                for j in children_data:
                    children = {}
                    children['open'] = 'true'
                    children['id'] = j.id
                    children['name'] = j.name
                    u.append(children)
                    x['children'] = u
                    # 三级目录
                    third_data = Department.objects.filter(pid=j.id).all()
                    if third_data:
                        o = []  # 三级目录容器
                        for k in third_data:
                            third_children = {}
                            third_children['open'] = 'true'
                            third_children['id'] = k.id
                            third_children['name'] = k.name
                            o.append(third_children)
                            children['children'] = o
                            # 四级目录
                            four_data = Department.objects.filter(pid=k.id).all()
                            if four_data:
                                p = []  # 四级目录容器
                                for g in four_data:
                                    four_children = {}
                                    four_children['open'] = 'true'
                                    four_children['id'] = g.id
                                    four_children['name'] = g.name
                                    p.append(four_children)
                                    third_children['children'] = p
            # 将部门数据集合
            top_dept.append(x)
        return JsonResponse(top_dept, safe=False)

    def post(self, request):
        id = request.POST.get('id')
        type = request.POST.get('type')
        name = request.POST.get('name')
        dept = request.POST.get('group')
        # 添加公司名称，顶级部门
        if dept:
            # 首先判断是否存在，存在则更新
            if Department.objects.filter(pid=0).all():
                Department.objects.filter(pid=0).update(name=dept)
                return JsonResponse({'status': 1, 'info': '修改成功'})
            else:
                new_Department = Department(name=dept, pid=0)
                new_Department.save()
                return JsonResponse({'status': 1, 'info': '添加完成！'})
        if type == 'add':
            # 前端点击添加按钮，默认在此部门下，创建一个部门
            status = Department.objects.filter(name='未命名').all()
            if status:
                return JsonResponse({'status': 0, 'info': '有未完成添加的部门，保存失败！'})
            else:
                new_dept = Department(name='未命名', pid=id)
                new_dept.save()
                return JsonResponse({'status': 1, 'info': '子部门添加成功，请点击编辑按钮设置部门名称。'})
        elif type == 'update':
            if id:
                if Department.objects.filter(id=id).update(name=name):
                    return JsonResponse({'status': 1, 'info': '部门名称修改成功！'})
                else:
                    return JsonResponse({'status': 0, 'info': '保存失败！'})
            elif name != '未命名':
                Department.objects.filter(name='未命名').update(name=name)
                return JsonResponse({'status': 1, 'info': '部门名称修改成功！'})
        elif type == 'del':
            # 首先判断此部门是否有下级部门，有则不允许删除
            if Department.objects.filter(pid=id).all():
                return JsonResponse({'status': 0, 'info': '此部门存在下级部门，不允许删除！'})
            # 其次判断此部门下是否有用户，有则不允许删除
            elif UserProfile.objects.filter(department_id=id).all():
                return JsonResponse({'status': 0, 'info': '此部门还存在用户，不允许删除！'})
            else:
                # 无下级部门，无用户，直接删除
                Department.objects.filter(id=id).delete()
                content_log = str(name) + '部门删除成功！'
                new_log = Log(username=request.user.username, content=content_log)
                new_log.save()
                return JsonResponse({'status': 1, 'info': '部门删除成功！'})
        else:
            return JsonResponse({'status': 0, 'info': '操作类型不允许！'})


# 新增用户角色
class AddNewRole(LoginRequiredMixin, View):
    def get(self, request):
        uid = request.user.id
        perms = check_custom_perms(7, uid, "read")
        if not perms:
            return render(request, 'deny.html')
        id_ = request.GET.get('id')
        if id_:
            role_name = Group.objects.filter(id=id_).all()[0].name
            return render(request, 'user/modify_role.html', {'role_name': role_name, 'role_id': id_})
        else:
            data = Group.objects.all()
            return render(request, 'user/role.html', {'data': data})

    def post(self, request):
        type_ = request.POST.get('type')
        role_id = request.POST.get('role_id')
        new_role = request.POST.get('new_role')
        # 开始判断操作
        if type_ == 'add':
            # 新增操作，需判断是否已经存在
            if Group.objects.filter(name=new_role).all():
                # 返回错误
                return JsonResponse({'status': 0, 'info': '不可重复添加！'})
            else:
                new_ = Group(name=new_role)
                new_.save()
                return JsonResponse({'status': 1, 'info': '新增成功！'})
        elif type_ == 'change':
            # 修改操作
            if role_id and new_role:
                Group.objects.filter(id=role_id).update(name=new_role)
                return JsonResponse({'status': 1, 'info': '更新成功！'})
            else:
                return JsonResponse({'status': 0, 'info': '数据不完整，更新失败！'})

        elif type_ == 'del':
            # 删除操作
            # 先判断是否有用户使用，若有，不允许删除
            if role_id:
                if UserProfile.objects.filter(role_id=role_id).all():
                    return JsonResponse({'status': 0, 'info': '此角色下还分配有用户，不允许直接删除！'})
                else:
                    Group.objects.filter(id=role_id).delete()
                    return JsonResponse({'status': 1, 'info': '删除成功！'})
        else:
            return JsonResponse({'status': 0, 'info': '不允许请求！'})


# 新增用户职位
class AddNewPosition(LoginRequiredMixin, View):
    def get(self, request):
        uid = request.user.id
        perms = check_custom_perms(5, uid, "read")
        if not perms:
            return render(request, 'deny.html')
        role_data = Position.role_choicse
        all_position = Position.objects.all()
        id_ = request.GET.get('id')
        if not id_:
            # 正常管理
            return render(request, 'user/position.html', {'role_data': role_data, 'all_position': all_position})
        else:
            # 修改界面
            # 摘取职位数据
            position_name = Position.objects.filter(id=id_).all()[0].name
            position_role = Position.objects.filter(id=id_).all()[0].get_role_display
            return render(request, 'user/modify_position.html',
                          {'role_data': role_data, 'position_role': position_role, 'position_name': position_name,
                           "position_id": id_})

    def post(self, request):
        type_ = request.POST.get('type')
        position_id = request.POST.get('position_id')
        new_position = request.POST.get('new_position')
        position_role = request.POST.get('position_role')
        # 开始判断操作
        if type_ == 'add':
            # 新增操作，需判断是否已经存在
            if Position.objects.filter(name=new_position).all():
                # 返回错误
                return JsonResponse({'status': 0, 'info': '不可重复添加！'})

            elif new_position and position_role:
                new_ = Position(name=new_position, role=position_role)
                new_.save()
                return JsonResponse({'status': 1, 'info': '新增成功！'})
            else:
                return JsonResponse({'status': 0, 'info': '数据不完整，添加失败！'})
        elif type_ == 'change':
            # 修改操作
            if position_id:
                if new_position:
                    Position.objects.filter(id=position_id).update(name=new_position, role=position_role)
                return JsonResponse({'status': 1, 'info': '更新成功！'})
            else:
                return JsonResponse({'status': 0, 'info': '数据不完整，更新失败！'})

        elif type_ == 'del':
            # 删除操作
            # 先判断是否有用户使用，若有，不允许删除
            if position_id:
                if UserProfile.objects.filter(position_id=position_id).all():
                    return JsonResponse({'status': 0, 'info': '此职位下还分配有用户，不允许直接删除！'})
                else:
                    Position.objects.filter(id=position_id).delete()
                    return JsonResponse({'status': 1, 'info': '删除成功！'})
        else:
            return JsonResponse({'status': 0, 'info': '不允许此请求！'})


# 站内信
class ShowMsg(LoginRequiredMixin, View):
    def get(self, request, type_):
        read_status = request.GET.get('read')
        mid = request.GET.get('mid')
        # 判断是否是标记已阅请求
        if read_status and mid:
            # 将消息标注为已阅
            Msg.objects.filter(id=mid).update(read_status=True, read_time=datetime.datetime.now())
            return JsonResponse({'status': 1, 'info': '已阅！'})
        else:
            # 查看历史记录
            if type_ == "system":
                # 用户接收到的来自系统的消息
                msg_info = Msg.objects.filter(receiver_id=1).all().order_by('-read_time', '-send_time')
            else:
                # 用户发送的消息以及用户接收到的来自用户的消息
                msg_info = Msg.objects.filter(Q(receiver_id=request.user.id) | Q(sender_id=request.user.id)).all().order_by(
                    '-read_time', '-send_time')
            return render(request, 'user/show_msg.html', {'msg_info': msg_info, 'type_': type_})

    def post(self, request):
        read_status = request.POST.get('read')
        mid = request.POST.get('mid')
        # 判断是否是标记已阅请求
        if read_status and mid:
            # 将消息标注为已阅
            Msg.objects.filter(id=mid).update(read_status=True, read_time=datetime.datetime.now())
            return JsonResponse({'status': 1, 'info': '消息状态标记为已阅读！'})
        else:
            return JsonResponse({'status': 0, 'info': '错误！'})


# 头像设置（头像上传）
class HeadPicUpload(LoginRequiredMixin, View):
    def get(self, request):
        return render(request, 'user/head_pic_upload.html')

    def post(self, request):
        uid = request.user.id
        head_pic = request.POST.get('head_pic')
        # 上传保存头像
        if uid and head_pic:
            user_ = UserProfile.objects.get(id=uid)
            # 前端用cropper裁减生成base64的图形，可以直接保存到数据库
            user_.head_pic = head_pic
            user_.save()
            return JsonResponse({'status': 1, 'info': '保存成功！'})
        else:
            return JsonResponse({'status': 0, 'info': '数据请求错误！'})


# 从excel导入用户
class ImportUserFromExcel(LoginRequiredMixin, View):
    def get(self, request):
        # 获取部门
        return render(request, 'user/import_user.html')

    def post(self, request):
        file = request.FILES.get('file')
        if file:
            # 保存文件
            # 开始保存
            # 文件命名更改为日期
            cur_day = datetime.datetime.now().strftime("%Y%m%d%H%M%S%f")
            # 提取文件后缀
            file_name = str(file)
            file_type = re.findall(r'\.[a-zA-Z_][a-zA-Z0-9_]*', file_name)
            new_name = cur_day + file_type[0]
            if str(file_type[0]) != ".xlsx":
                if str(file_type[0]) != ".XLSX":
                    return JsonResponse({"status": 0, "info": "文件格式必须为xlsx!"})
            else:
                # 保存文件
                file_path = os.path.join(BASE_DIR, 'static', 'upload', new_name)
                open_file_path = open(file_path, 'wb+')
                for chunk in file.chunks():
                    open_file_path.write(chunk)
                open_file_path.close()
                # 文件保存完毕
                # 开始读取文件内容，添加用户
                df = pandas.read_excel(file_path)
                # 1,获取数据行数
                row_len = len(df)
                row = 0
                # 成功计数
                success_num = 0
                # 密码设置为admin123@
                password = 'pbkdf2_sha256$216000$KLneLROEK49e$QFWZIsOJI5xe87ha6Qk9NHrxvwMG35nneffXAs63IIo='
                info_error = ''
                import_contents = []
                # 循环获取每一行的数据
                while row < int(row_len):
                    row_values = df.loc[row].values
                    # 获取到行的数据后，赋值
                    username = row_values[0]
                    phone = row_values[1]
                    email = row_values[2]
                    dept = row_values[3]
                    direct_leader = row_values[4]
                    role = row_values[5]
                    position = row_values[6]
                    is_staff = row_values[7]
                    if is_staff:
                        if is_staff == '是':
                            is_staff = 1
                        else:
                            is_staff = 0
                    else:
                        is_staff = 0
                    # 开始处理部门
                    # 如果部门不存在，则返回错误
                    if str(dept) != 'nan':
                        if Department.objects.filter(name=dept):
                            dept = Department.objects.filter(name=dept).all()
                            dept = dept[0].id
                            # 部门完整的情况下，检查用户角色
                            if str(role) != 'nan':
                                Group.objects.get_or_create(name=role)
                                role = Group.objects.filter(name=role).all()
                                role = role[0].id
                                # 检测用户职位
                                if str(position) != 'nan':
                                    Position.objects.get_or_create(name=position)
                                    position = Position.objects.filter(name=position).all()
                                    position = position[0].id
                                # 关键数据处理完成，开始保存
                                # 如果用户不存在，则开始保存【用户名，邮箱，手机号均需要唯一】
                                if not UserProfile.objects.filter(
                                        Q(username=username) | Q(mobile=phone) | Q(email=email)):
                                    # 开始保存
                                    import_contents.append({
                                        'username': username, 'email': email, 'dept_id': dept, 'is_staff': is_staff,
                                        'role_id': role, 'mobile': phone, 'position_id': position,
                                        'd_leader': direct_leader,
                                    })
                                    # 保存成功，则成功计数+1
                                    success_num = success_num + 1
                            else:
                                info_error = '角色为必填，请重新整理excel数据！'

                        else:
                            info_error = dept + '-部门不存在，请联系管理员维护部门！'
                    else:
                        info_error = '部门为必填，请重新整理excel数据！'
                    row = row + 1
                # 循环结束，返回成功计数
                if info_error:
                    # 返回错误
                    return JsonResponse({'status': 0, 'info': info_error})
                # 没有错误，开始保存
                for j in import_contents:
                    new_user = UserProfile(username=j['username'], email=j['email'], department_id=j['dept_id'],
                                           is_staff=j['is_staff'], role_id=j['role_id'], mobile=j['mobile'],
                                           is_active=1, is_superuser=0, position_id=j['position_id'],
                                           password=password, direct_leader=j['d_leader'])
                    new_user.save()
                info_success = '合计：' + str(row_len) + '个用户，本次成功导入：' + str(success_num) + '个用户！'
                return JsonResponse({'status': 1, 'info': info_success})
        else:
            return JsonResponse({'status': 0, 'info': '您还没选择文件！'})


# 扫码后绑定已有账户
class AttachUserToScanLogin(View):
    def get(self, request, type_, id_):
        return render(request, 'user/login_v3_attach.html', {"tpye_": type_})

    def post(self, request, type_, id_):
        user_name = request.POST.get("username")
        password = request.POST.get("password")
        if user_name and password:
            u_id = UserProfile.objects.filter(Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name)).all()
            if not u_id:
                return render(request, 'user/login_v3.html', {'msg': '用户不存在！'})
            else:
                # 检测用户是否输入了正确的密码
                user = authenticate(username=user_name, password=password)
                if user:
                    # 验证成功
                    # 开始绑定
                    user_data = UserProfile.objects.get(
                        Q(username=user_name) | Q(mobile=user_name) | Q(email=user_name))
                    if type_ == "ent_wechat":
                        # 企业微信
                        user_data.open_id = id_
                    elif type_ == "wechat":
                        user_data.union_id = id_
                    else:
                        # 钉钉
                        user_data.dingtalk_id = id_
                    # 绑定完毕
                    user_data.save()
                    return JsonResponse({"status": 1, "info": "绑定成功，请重新扫码登录！"})
                else:
                    return JsonResponse({'status': 0, "info": "密码输入错误！"})
        else:
            return JsonResponse({'status': 0, "info": "用户名和密码是必填的哦！"})


# 微信扫码登录
class ShowEntWechatQR(View):
    def get(self, request):
        return render(request, 'user/login_v3_wechat.html', {'Corpid': Corpid_, 'Login_Agentid': Login_Agentid,
                                                             'redirect_uri': Redirect_uri})


# 扫码后验证登录
class EntWechatLogin(View):
    def get(self, request):
        # 1, 获取Code
        code = request.GET.get("code")
        if code:
            # 2，获取access_token
            def GetToken(Corpid, Secret):
                Url = "https://qyapi.weixin.qq.com/cgi-bin/gettoken"
                Data = {
                    "corpid": Corpid,
                    "corpsecret": Secret
                }
                r = requests.get(url=Url, params=Data)
                Token = r.json()['access_token']
                return Token

            # 2.2 获取用户信息
            def GetUserId(token_, code_):
                Url = "https://qyapi.weixin.qq.com/cgi-bin/user/getuserinfo"
                Data = {
                    "access_token": token_,
                    "code": code_
                }
                r = requests.get(url=Url, params=Data)
                user_info = r.json()
                return user_info

            # 2.3 UserId转OpenId
            def GetOpenId(UID, token_):
                Url = "https://qyapi.weixin.qq.com/cgi-bin/user/convert_to_openid?access_token=" + token_
                Data = {
                    "userid": "LiuJianGuang"
                }
                headers = {
                    "Content-Type": "application/json"
                }
                r = requests.post(url=Url, data=json.dumps(Data), headers=headers)  # post 传入参数data，get传入参数params
                print(r.json())
                if r.json()['errmsg'] == "ok":
                    # 请求成功
                    OpenId = r.json()['openid']
                else:
                    OpenId = False
                return OpenId

            Token = GetToken(Corpid_, Login_Scret)
            if Token:
                UserInfo = GetUserId(Token, code)
                if UserInfo:
                    # 先判断是否返回了错误
                    if not UserInfo['errcode']:
                        # 没错误
                        if UserInfo["UserId"]:
                            # 获取到内部成员Id
                            print("UserId", UserInfo['UserId'])
                            # 根据UserId获取OpenId, OpenId对同企业内部人员而言是唯一的，但是对外部人员不唯一，
                            # 所以，用于内部登录场景不会存在重复的情况
                            openid = GetOpenId(UserInfo["UserId"], Token)
                            if openid:
                                # 请求成功
                                # 1, 检查是否绑定
                                if UserProfile.objects.filter(open_id=openid):
                                    # 已有绑定
                                    # 登录用户
                                    user = UserProfile.objects.get(open_id=openid)
                                    login(request, user)
                                    return HttpResponseRedirect(reverse("index"))
                                else:
                                    # 没有绑定，跳转绑定页面
                                    return redirect("/login/attach/ent_wechat/" + openid)
                            else:
                                return render(request, 'user/login_v3_wechat.html', {'Corpid': Corpid_,
                                                                                     'Login_Agentid': Login_Agentid,
                                                                                     'redirect_uri': Redirect_uri,
                                                                                     'msg': 'UID转OID失败，请联系管理员！',
                                                                                     })
                        elif UserInfo["OpenId"]:
                            # 获取到的是外部人员的Id
                            # 获取到的是外部企业人员，不允许登录
                            return render(request, 'user/login_v3_wechat.html', {'Corpid': Corpid_,
                                                                                 'Login_Agentid': Login_Agentid,
                                                                                 'redirect_uri': Redirect_uri,
                                                                                 'msg': '仅允许企业内部人员登录！',
                                                                                 })
                        else:
                            # 未能成功获取返回值
                            return render(request, 'user/login_v3_wechat.html', {'Corpid': Corpid_,
                                                                                 'Login_Agentid': Login_Agentid,
                                                                                 'redirect_uri': Redirect_uri,
                                                                                 'msg': '获取用户信息失败，请联系管理员！',
                                                                                 })

                    else:
                        return render(request, 'user/login_v3_wechat.html', {'Corpid': Corpid_,
                                                                             'Login_Agentid': Login_Agentid,
                                                                             'redirect_uri': Redirect_uri,
                                                                             'msg': UserInfo["errmsg"],
                                                                             })
                else:
                    return render(request, 'user/login_v3_wechat.html', {'Corpid': Corpid_,
                                                                         'Login_Agentid': Login_Agentid,
                                                                         'redirect_uri': Redirect_uri,
                                                                         'msg': '没有获取到UserId，请联系管理员！',
                                                                         })
            else:
                return render(request, 'user/login_v3_wechat.html', {'Corpid': Corpid_,
                                                                     'Login_Agentid': Login_Agentid,
                                                                     'redirect_uri': Redirect_uri,
                                                                     'msg': '没有获取到Token，请联系管理员！',
                                                                     })

        else:
            return render(request, 'user/login_v3_wechat.html', {'Corpid': Corpid_,
                                                                 'Login_Agentid': Login_Agentid,
                                                                 'redirect_uri': Redirect_uri,
                                                                 'msg': '没有获取到code，请联系管理员！',
                                                                 })


# 菜单管理
# 开发新的模块，开启新的VIEW视图，则在此模块WEB前端添加菜单，其URL和url.py的路径一致，授权根据菜单来确定
# 左侧的导航菜单根据权限，自动渲染生成

class MenuView(LoginRequiredMixin, View):
    def get(self, request):
        uid = request.user.id
        # 权限判断

        # 权限通过
        # 开始处理菜单数据，最大3级
        data = []
        # 1，一级菜单
        data_1 = Menu.objects.filter(pid=0).all()
        for x1 in data_1:
            data.append({
                "id": x1.id, "name": str(x1.icon) + str(x1.name), "pid": x1.pid
            })
            # 二级菜单
            data_2 = Menu.objects.filter(pid=x1.id).all()
            if data_2:
                for x2 in data_2:
                    data.append({
                        "id": x2.id, "name": str(x2.icon) + str(x1.name), "pid": x2.pid
                    })
        data = Menu.objects.all()
        return render(request, "user/menu.html", {"data": data})

    # 新增一级菜单
    def post(self, request):
        name = request.POST.get("name")
        icon = request.POST.get("icon")
        order_num = request.POST.get("order_num")
        if name:
            if not icon:
                icon = '''<i class="nav-icon fas fa-tree"></i>'''
            if not Menu.objects.filter(name=name, pid=0):
                # 没有相同名称的一级菜单
                new = Menu(name=name, icon=icon, pid=0, url="#", order_num=order_num)
                new.save()
                return JsonResponse({"status": 1, "info": "保存成功！"})
            else:
                return JsonResponse({"status": 0, "info": "已有相同名称的一级菜单！"})
        else:
            return JsonResponse({"status": 0, "info": "数据不完整！"})


# 修改菜单（菜单名称，icon），其他信息不允许修改
class EditMenuView(LoginRequiredMixin, View):
    def get(self, request, mid, action):
        if action == "修改":
            # 修改操作
            data = Menu.objects.filter(id=mid).all()
            return render(request, "user/menu_edit.html", {"data": data})
        else:
            # 新增子菜单操作
            return render(request, "user/menu_add.html")

    def post(self, request, mid, action):
        name = request.POST.get("name")
        icon = request.POST.get("icon")
        url = request.POST.get("url")
        order_num = request.POST.get("order_num")
        if action == "修改":
            # 只允许修改名称，icon，order_num
            if not icon:
                icon = '''<i class="nav-icon fas fa-tree"></i>'''
            if not url:
                url = "#"
            data = Menu.objects.get(id=mid)
            if name == data.name:
                pass
            # 同级目录下不能有重复
            elif Menu.objects.filter(name=name, pid=data.pid).exclude(id=mid):
                # 有重复
                return JsonResponse({"status": 0, "info": "同级别菜单下已有相同名称的菜单！"})
            else:
                data.name = name
            data.icon = icon
            data.order_num = order_num
            data.save()
            return JsonResponse({"status": 1, "info": "保存成功！"})
        else:
            # 新增子菜单操作
            if name and url:
                if not icon:
                    icon = ''
                if not order_num:
                    order_num = 1000
                # 同级别下面不能有重复菜单名
                if not Menu.objects.filter(pid=mid, name=name):
                    new = Menu(name=name, url=url, icon=icon, order_num=order_num, pid=mid)
                    new.save()
                    return JsonResponse({"status": 1, "info": "保存成功！"})
                else:
                    return JsonResponse({"status": 0, "info": "同级菜单目录不能有重复的名称！"})
            else:
                return JsonResponse({"status": 0, "info": "数据不完整！"})
